let that
class Drag {
    constructor(data){
        this.box=data.box
        this.size=data.size
        this.maxTop=data.maxTop   ||    document.documentElement.clientHeight - data.size  || 1000 
        this.maxLeft=data.maxLeft  ||   document.body.scrollWidth  - data.size  || 1280

        this.halfTop=parseInt(this.maxTop /2)
        this.halfLeft=parseInt(this.maxLeft /2)

        this.duration = data.duration
        that=this
    }

    init(){ //初始化
        this.box.style.posisition = 'fixed'
        this.box.style.transitionDuration = '0s'
        this.box.onmousedown=this.star.bind(this)
    }
    star(e){
         let box = this.box
         box.x=e.pageX-box.offsetLeft
         box.y=e.pageY-box.offsetTop
         document.addEventListener("mousemove",this.move,false)
         document.onmouseup=this.end.bind(this)
    }
    limit(size,min,max){
        if(size <= min) return min
        if(size>=max) return max
        return size
    }

    move(e){
        let box =that.box
        let newLeft = that.limit(e.pageX-box.x,0,that.maxLeft)
        let newTop = that.limit(e.pageY-box.y,0,that.maxTop)
        box.style.left=newLeft+"px"
        box.style.top=newTop+"px"
    }

    end(e){
        document.removeEventListener("mousemove",this.move,false)
        document.onmouseup=null
        if( !this.box.style.left || parseInt(this.box.style.left)>this.halfLeft) 
          {
            this.box.style.right ='10px'
             this.box.style.left = null
          }
        else {
            this.box.style.left ='10px'
            this.box.style.right = null
        }
        
        this.box.style.bottom = this.maxTop - parseInt(this.box.style.top)  +'px'
        this.box.style.top=null
    }
    uninit(){
        this.box.onmousedown = null
        this.box.style.transitionDuration = this.duration
    }
}
export default Drag